package com.base.springboot.starter.mybatisplus.service;

import com.base.common.exception.CommonRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

/**
 * SQL过滤
 *
 * @author admin
 * @date 2020/5/19 AM10:15
 */
@Slf4j
public class SqlFilter {
    private SqlFilter() {
        log.info("starter: SqlFilter init...");
    }

    /**
     * SQL注入过滤
     *
     * @param str 待验证的字符串
     */
    public static String sqlInject(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        //去掉'|"|;|\字符
        str = StringUtils.replace(str, "'", "");
        str = StringUtils.replace(str, "\"", "");
        str = StringUtils.replace(str, ";", "");
        str = StringUtils.replace(str, "\\", "");

        //转换成小写
        str = str.toLowerCase();
        //非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alert", "drop"};

        //判断是否包含非法字符
        for (String keyword : keywords) {
            if (str.indexOf(keyword) != -1
                    && !"insertdate".equals(str)
                    && !"insertuserid".equals(str)
                    && !"insertusername".equals(str)
                    && !"updatedate".equals(str)
                    && !"updateusername".equals(str)
                    && !"updateuserid".equals(str)) {
                throw new CommonRuntimeException("包含非法字符");
            }
        }

        return str;
    }
}
